<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="./js/jquery.js"></script>
  <title>Document</title>
  <style>
    #sliding {
      cursor: pointer;
      border-radius: 10px;
    }

    input[type=range] {
      -webkit-appearance: none;
      background: linear-gradient(to right, #FF710C 50%, #ddd 0%);
      height: 13px;
    }

    input[type=range]::-webkit-slider-thumb {
      -webkit-appearance: none;
      background: white;
      height: 13px;
      width: 13px;
      border-radius: 50%;
    }
  </style>
</head>

<body>
  <h1 id="title">0</h1>
  <!-- min 最左边的值，max 最右边的值，step 滑动时增加的基数 -->
  <input type="range" id="sliding" min='-100' max="100" step='1'>
</body>

</html>


<script>

  /** 滑动块儿
   * @param el            input 元素 id (必填)
   * @param titleEl       标签 id 或者 class (可填)
   * @param startColor    开始颜色 (默认 #FF710C) (可填) 注意：css 也要同步填写
   * @param endColor      结束颜色 (默认 #ddd) (可填) 注意：css 也要同步填写
   * @param callback(val) 鼠标滑动回调函数 val 返回 input 值 (可填)     
   * @param sliding(val)  鼠标抬起回调函数 val 返回 input 值 (可填)
  */
  function slider({ el, titleEl, startColor = "#FF710C", endColor = "#ddd", callback, sliding }) {
    if (!el) {
      console.error("请填写input id");
    }
    var min = $(el).attr('min')
    var max = $(el).attr('max')
    var step = $(el).attr('step')
    $(el).on('input propertychange', function () {
      var val = $(el).val()
      var progressNum = max - min
      var halfNum = progressNum / 2
      var residue
      if (val < 0) {
        var _val = Math.abs(val)
        residue = halfNum - _val
        residue = (residue / progressNum) * 100
      }
      if (val > 0) {
        residue = ((halfNum + Number(val)) / progressNum) * 100
      }
      titleEl && $(titleEl).text(val)
      $(el).css({ 'background': `linear-gradient(to right,${startColor} ${residue}%, ${endColor} 0%)` })
      sliding && sliding(val)
    })
    $(el).mouseup(() => {
      var val = $(el).val()
      callback && callback(val)
    })
  }

  slider({
    el: '#sliding',
    titleEl: '#title',
    callback: function (val) {
      console.log('鼠标抬起事件', val);
    },
    sliding: function (val) {
      console.log('滑动时触发', val);
    }
  })

</script>